package com.paas.demo.config;

import com.paas.demo.common.PJson;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SuppressWarnings("ALL")
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public PJson errorHandler(Exception ex) {

        logger.error(ex.getMessage(), ex);

        return PJson.fail().msg("系统内部出现异常，请稍后再试。");
    }

    //不满足@RequiresGuest注解时抛出的异常信息
    private static final String GUEST_ONLY = "Attempting to perform a guest-only operation";


    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public PJson handleShiroException(ShiroException e) {
        String eName = e.getClass().getSimpleName();
        logger.error("shiro执行出错：{}",eName);
        return new PJson(eName, false, PJson.DEFAULT_FAIL_CODE, "鉴权或授权过程出错", null);
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public PJson page401(AuthorizationException e) {
        String eMsg = e.getMessage();
        if (StringUtils.startsWithIgnoreCase(eMsg,GUEST_ONLY)){
            return new PJson("401", false, PJson.DEFAULT_FAIL_CODE, "只允许游客访问，若您已登录，请先退出登录", null)
                    .data("detail",e.getMessage());
        }else{
            return new PJson("401", false, PJson.DEFAULT_FAIL_CODE, "用户未登录", null)
                    .data("detail",e.getMessage());
        }
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public PJson page403() {
        return new PJson("403", false, PJson.DEFAULT_FAIL_CODE, "用户没有访问权限", null);
    }
}
